<template>
  <el-form ref="ruleFormRef" :model="formData" :rules="formRules" size="small" :inline="false" label-width="100px">
    <el-form-item label="主题" prop="title">
      <el-input v-model="formData.title" placeholder="请填写主题" maxlength="32" size="small"/>
    </el-form-item>
    <el-form-item label="员工" prop="staffId">
      <el-select v-model="formData.staffId" placeholder="请选择员工" size="small" filterable @change="getStaffDetail">
        <el-option v-for="item in staffList" :key="item.id" :value="item.id" :label="item.name"/>
      </el-select>
    </el-form-item>
    <el-form-item label="异动类型" prop="changeType">
      <el-select v-model="formData.changeType" placeholder="请选择异动类型" size="small">
        <el-option v-for="item in dictMap['StaffChangeType']" :key="item.value" :value="item.value" :label="item.name"/>
      </el-select>
    </el-form-item>
    <el-form-item label="生效日期" prop="occurDate">
      <el-date-picker v-model="formData.occurDate" type="date" placeholder="请选择生效日期" size="small" value-format="YYYY-MM-DD"/>
    </el-form-item>
    <el-row style="margin-bottom: 18px">
      <el-col :span="12">
        <el-form-item label="原部门" prop="originalDeptId">{{ originStaffData.dept ? originStaffData.dept.name : '-' }}</el-form-item>
        <el-form-item label="原职位" prop="originalPositionId">
          <span>{{ originStaffData.officePosition ? originStaffData.officePosition.name : '-' }}</span>
          <span style="margin: 0 25px" v-if="originStaffData.officePosition">职级：{{ originStaffData.officePosition.gradeName || '-' }}</span>
          <span v-if="originStaffData.officePosition">职等：{{ originStaffData.officePosition.grade || '-' }}</span>
        </el-form-item>
        <el-form-item label="原职务" prop="originalPostId">{{ originStaffData.officePost ? originStaffData.officePost.name : '-' }}</el-form-item>
        <el-form-item label="原直属上级" prop="directSuperiorId">{{ originStaffData.directSuperiorName || '-' }}</el-form-item>
        <el-form-item label="原工作地点" prop="originalWorkAddress">{{ originStaffData.workAddress || '-' }}</el-form-item>
      </el-col>
      <el-col :span="12">
        <el-form-item label="新部门" prop="oaDeptId">
          <el-tree-select v-model="formData.oaDeptId" node-key="id" value-key="id" :props="{ value: 'id', label: 'name'}" :data="deptList" check-strictly :render-after-expand="false" filterable size="small"/>
        </el-form-item>
        <el-form-item label="新职位" prop="oaPositionId">
          <el-select v-model="selectedPosition" placeholder="请选择新职位" value-key="id" size="small" filterable @change="positionChange">
            <el-option v-for="item in positionList" :key="item.value" :value="item" :label="item.name"/>
          </el-select>
          <span style="margin: 0 25px" v-if="selectedPosition.officeGrade">职级：{{ selectedPosition.officeGrade.name || '-' }}</span>
          <span v-if="selectedPosition.officeGrade">职等：{{ selectedPosition.officeGrade.grade || '-' }}</span>
        </el-form-item>
        <el-form-item label="新职务" prop="postId">
          <el-select v-model="formData.postId" placeholder="请选择新职务" size="small" filterable>
            <el-option v-for="item in postList" :key="item.id" :value="item.id" :label="item.name"/>
          </el-select>
        </el-form-item>
        <el-form-item label="新直属上级" prop="directSuperiorId">
          <el-select v-model="formData.directSuperiorId" placeholder="请选择新直属上级" size="small" filterable>
            <el-option v-for="item in staffList" :key="item.id" :value="item.id" :label="item.name" :disabled="item.id == formData.staffId"/>
          </el-select>
        </el-form-item>
        <el-form-item label="新工作地点" prop="workAddress">
          <el-input v-model="formData.workAddress" placeholder="请填写新工作地点" size="small"/>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item label="异动原因" prop="content">
      <editor v-model="formData.content" />
    </el-form-item>
    <el-form-item label="优先度" prop="priority">
      <el-radio-group v-model="formData.priority" size="small">
        <el-radio :label="0" size="small">普通</el-radio>
        <el-radio :label="1" size="small">高</el-radio>
      </el-radio-group>
    </el-form-item>
    <el-form-item label="备注信息" prop="remark">
      <el-input v-model="formData.remark" type="textarea" :rows="3" placeholder="请填写备注信息" size="small"/>
    </el-form-item>

  </el-form>
</template>

<script>
// 异动事项 OA_POSITION_CHANGE
import {onMounted, reactive, toRefs, ref, nextTick, watch} from 'vue'
import {getDictByCodes} from '/@/api/sys/dict'
import {getSelectorData, getStaffById} from '/@/api/oa/staff'
import {getTreeList} from '/@/api/oa/dept'
import {getSelectorList} from '/@/api/oa/office/post'
import {getPositionSelector} from '/@/api/oa/office/position'
import Editor from '/@/components/editor/index.vue'
import {homeApi} from "/@/api/home/index";
import { useCalendarConfig } from '/@/stores/calendar';
import { storeToRefs } from 'pinia';

export default {
  name: 'Reshuffle',
  components: {
    Editor
  },
  props: {
    selectTime: {
      type: String,
      default: null
    },
    editId: {
      type: String,
      default: null
    }
  },
  setup(props) {
    const { selectTime, editId } = toRefs(props)
    const homeCalendar = homeApi();
    const ruleFormRef = ref()
    const storesCalendarConfig = useCalendarConfig();
    const { eventForm } = storeToRefs(storesCalendarConfig)
    const state = reactive({
      formData: {
        title: '员工异动',
        staffId: null,
        changeType: null,   // 异动类型 字典StaffChangeType
        content: null,     // 原因
        occurDate: null,  // 生效日期
        originalDeptId: null,   // 原部门id
        originalPositionId: null, // 原职位id
        originalPostId: null, // 原职务id
        originalSuperiorId: null, // 原直属上级（员工）id
        originalWorkAddress: null,  // 原工作地点
        oaDeptId: null,   // 新部门id
        oaPositionId: null,   // 新职位id
        postId: null, // 新职务id
        directSuperiorId: null,   // 新直属上级id
        workAddress: null,    // 新工作地点
        remark: null,   // 备注信息
        state: 2,           // 状态 -1草稿 0未开始 1进行中 2已完成 3已退回  4已取消 5已撤回
        priority: 0        // 优先级 0普通 1重要
      },
      formRules: {
        title: {required: true, message: '请填写主题', trigger: 'blur'},
        staffId: {required: true, message: '请选择员工', trigger: 'change'},
        changeType: {required: true, message: '请选择异动类型', trigger: 'change'},
        occurDate: {required: true, message: '请选择生效日期', trigger: 'change'},
        content: {required: true, message: '请填写异动原因', trigger: 'blur'}
      },
      originStaffData: {},    // （原）员工数据
      selectedPosition: {},   // 选中的新职位详细数据
      dictMap: {},
      staffList: [],
      deptList: [],
      postList: [],
      positionList: [],
      originForm: {}
    })
    const getStaffData = async () => {
      try {
        const res = await getSelectorData()
        state.staffList = res.data
      } catch (e) {
        console.log(e)
      }
    }
    const getDeptData = async () => {
      try {
        const res = await getTreeList()
        state.deptList = res.data
      } catch (e) {
        console.log(e)
      }
    }
    const getPostData = async () => {
      try {
        const res = await getSelectorList()
        state.postList = res.data
      } catch (e) {
        console.log(e)
      }
    }
    const getPositionData = async () => {
      try {
        const res = await getPositionSelector()
        state.positionList = res.data
      } catch (e) {
        console.log(e)
      }
    }
    const getStaffDetail = async (val) => {
      if (val == state.formData.directSuperiorId) {
        state.formData.directSuperiorId = null
      }
      try {
        const res = await getStaffById(val)
        state.originStaffData = res.data
        state.formData.originalDeptId = state.originStaffData.oaDeptId
        state.formData.originalPositionId = state.originStaffData.postId
        state.formData.originalPostId = state.originStaffData.dutyId
        state.formData.originalSuperiorId = state.originStaffData.directSuperiorId
      } catch (e) {
        console.log(e)
      }
    }
    const positionChange = async (val) => {
      if (val) {
        state.formData.oaPositionId = val.id
      } else {
        state.formData.oaPositionId = null
      }
    }
    const submit = () => {
      if(!ruleFormRef) return
       return new Promise(async (resolve, reject) => {
        await ruleFormRef.value.validate((valid, fields) => {
          if (valid) {
              if(editId.value) {
                // 编辑
                for(let key in state.formData){
                  if(state.originForm.hasOwnProperty(key)){
                    state.originForm[key] = state.formData[key]
                  }
                  if(state.originForm.info.hasOwnProperty(key)){
                    state.originForm.info[key] = state.formData[key]
                  }
                }
                storesCalendarConfig.setEventForm(state.originForm)
                reset()
                close()
                resolve('edit') 
              }else{
                homeCalendar.addPositionChange(state.formData).then((res) => {
                  if (res.code === 0) {
                    reset()
                    close()
                    resolve()
                  }
                });
              }
          } else {
              reject()
              console.log("error submit!", fields);
          }
        })  
       })
    }
    const reset = () => {
      if (!ruleFormRef) return
      ruleFormRef.value.resetFields()
    }
    watch(() => eventForm.value,
      val => {
        if(editId.value && val) {
          // 编辑
          nextTick(() => {
            const data = val
            if(!data) return
            state.originForm = data
            for(let params in data.info){
              // 拿出info里面的数据
              if(state.formData.hasOwnProperty(params)) {
                state.formData[params] = data.info[params]
              }
            }
            for(let key in data) {
              // 列表里面的数据
              if(state.formData.hasOwnProperty(key)) {
                state.formData[key]= data[key]
              }
            }
          })
        }
      }        
    )
    onMounted(() => {
      getDictByCodes(['StaffChangeType']).then(res => state.dictMap = res.data)
      getStaffData()
      getPostData()
      getPositionData()
      getDeptData()
      if (state.formData.staffId) {
        getStaffDetail(state.formData.staffId)
      }
      nextTick(() => {
        if(!editId.value && selectTime.value) {
          state.formData.occurDate = selectTime.value.substring(0, 10)
        }
      })
    })

    return {
      ...toRefs(state),
      getStaffData,
      getDeptData,
      getPostData,
      getPositionData,
      getStaffDetail,
      positionChange,
      ruleFormRef,
      submit,
      reset
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
